package com.ruoyi.netty.client;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

/**
 * @Author 阿飞
 * @Date 2023/11/14 14:10
 */
@Component
@ChannelHandler.Sharable
public class CharServer {
    @PostConstruct
    public void start(){
        //创建线程组
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //服务器引导
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress("localhost",8564))
                    //引入注册
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(4096, Unpooled.copiedBuffer("#$&*".getBytes())));
                            ch.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new NettyClientHandler());//业务
                        }
                    });
            ChannelFuture future = serverBootstrap.bind().sync();//再试试 欧克欧克
            if(future.isSuccess()){
                System.out.println(CharServer.class.getName() + " started and listen on " + future.channel().localAddress());
            }
        } catch (Exception e) {
            e.printStackTrace();
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
